/**
 * Created by syz on 2016/1/13.
 */

var https = require('https');
var crypto = require('crypto');

function sendTemplateSms(to, datas, templateId, cb) {
  // http://www.yuntongxun.com/
  //主帐号
  var accountSid = '8a48b5515185cb1a01518b2548fe0858';
  //主帐号Token
  var accountToken = '038e01a0ecfd4b53805b7e79d5e3994f';
  //应用Id
  var appId = '8a216da85c62c9ad015c854ae2a40c30';
  //var appId = '8a48b5515185cb1a01518b279508085d';   //demo 用
  //请求地址，格式如下，不需要写https://
  //var serverHost='sandboxapp.cloopen.com';
  var serverHost='app.cloopen.com';
  //请求端口
  var serverPort='8883';
  //REST版本号
  var softVersion='2013-12-26';

  var body = JSON.stringify({
    to : to,
    templateId : templateId,
    appId: appId,
    datas: datas
  });

  //console.log(body);
  var date = new Date();
  var timeStr = new Date(date.getTime() - date.getTimezoneOffset()*60000).toISOString().replace(/[T|\-|\:]/g, '').replace(/\..+/, '');
  //console.log(timeStr);
  var md5 = crypto.createHash('md5');
  md5.update(accountSid + accountToken + timeStr);
  var sig = md5.digest('hex');

  var path = '/'+ softVersion + '/Accounts/' + accountSid + '/SMS/TemplateSMS?sig=' + sig.toUpperCase();
  var b = new Buffer(accountSid + ':' + timeStr);
  var auth = b.toString('base64');

  var options = {
    host : serverHost,
    port: serverPort,
    path : path,
    method : 'POST',
    headers : {
      'Authorization': auth,
      'Accept': 'application/json',
      'Content-Type' : 'application/json;charset=utf-8',
      'Content-Length' : Buffer.byteLength(body)
    }
  };

  var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(body) {
      try{
        var ret = JSON.parse(body);
        cb(null, ret);
      }catch(err){
        cb(err);
      }
    });
  });

  req.on('error', function(e) {
    cb(e, null);
  });

  // write data to request body
  req.write(body);
  req.end();
};


module.exports.sendTemplateSms  = sendTemplateSms;
